<template>
  <section>
    <!--工具条 - 高级查询框-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="query">
        <el-form-item>
          <el-input v-model="query.keyword" placeholder="请输入关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
<!-- 商家入驻-->
        <el-form-item>
          <el-button type="primary" @click="addshop">商家入驻</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="shop.rows" highlight-current-row v-loading="listLoading" height="650" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55" fixed>
      </el-table-column>
      <el-table-column type="index" width="60" fixed>
      </el-table-column>
      <el-table-column prop="name" label="名称" fixed width="230" sortable>
      </el-table-column>
      <el-table-column prop="logo" label="Logo" width="120" sortable>
        <template slot-scope="scope">
          <img :src="scope.row.logo" width="60px" height="60px">
        </template>
      </el-table-column>

      <el-table-column prop="name" label="店铺名称" width="200" sortable>
      </el-table-column>
      <el-table-column prop="address" label="店铺地址" width="200" sortable>
      </el-table-column>

      <!--当前审核状态-->
      <el-table-column prop="state" label="审核状态" min-width="90" sortable>
        <template slot-scope="scope">
          <span v-if="scope.row.state == 1" style="color:#E6A23C">待审核</span>
          <span v-if="scope.row.state == 2" style="color:lightgreen">待激活</span>
          <span v-if="scope.row.state == 3" style="color:#409EFF">通过</span>
          <span v-if="scope.row.state == 4" style="color: #ff4d51">驳回</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="350" fixed="right">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="(scope.$index, scope.row)">驳回</el-button>
          <el-button type="success" size="small" @click="(scope.$index, scope.row)">通过</el-button>
        </template>
      </el-table-column>



    </el-table>


    <!--工具条 批量删除&分页条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量操作</el-button>
      <el-pagination
          layout="prev, pager, next"
          :current-page="query.currentpage"
          @current-change="handleCurrentChange"
          :page-size="query.pageSize"
          :total="pageInfo.total"
          style="float:right;">
      </el-pagination>
    </el-col>

    <!--新增界面-->
    <el-dialog title="新增/修改" :visible.sync="carFormVisible" :close-on-click-modal="false">
      <el-form :model="carForm" label-width="80px"  ref="carForm">
        <el-form-item label="标题">
          <el-input v-model="carForm.title" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="封面">
          <el-upload
              class="upload-demo"
              action="http://localhost:8081/commons/upload"
              :on-remove="coverHandleRemove"
              :on-success="coverHandleSuccess"
              :file-list="coverFileList"
              list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="原价">
          <el-input v-model="carForm.saleprice" style="width:220px;" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="售价">
          <el-input v-model="carForm.costprice" style="width:220px;" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="是否新车">
          <el-radio-group v-model="carForm.isnew">
            <el-radio class="radio" :label="1">是</el-radio>
            <el-radio class="radio" :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="上牌时间">
          <el-date-picker
              value-format="yyyy-MM-dd"
              v-model="carForm.reigstertime"
              type="date"
              placeholder="请选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="里程数">
          <el-input v-model="carForm.mileage" style="width:220px;" type="number" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="超值">
          <el-radio-group v-model="carForm.costeffective">
            <el-radio class="radio" :label="1">是</el-radio>
            <el-radio class="radio" :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="急售">
          <el-radio-group v-model="carForm.rushsale">
            <el-radio class="radio" :label="1">是</el-radio>
            <el-radio class="radio" :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="准新车">
          <el-radio-group v-model="carForm.quasinewcar">
            <el-radio class="radio" :label="1">是</el-radio>
            <el-radio class="radio" :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="可迁全国">
          <el-radio-group v-model="carForm.transitivecountry">
            <el-radio class="radio" :label="1">是</el-radio>
            <el-radio class="radio" :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="品牌">
          <el-select v-model="carForm.brand" placeholder="请选择">
            <!-- v-for 循环cartypes 得到cartype-->
            <el-option

                v-for="cartype in cartypes"
                :key="cartype.value"
                :label="cartype.name"
                :value="cartype.name">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="车辆类型">
          <el-cascader v-model="carForm.type"
                       :options="carTypeTree"
                       :props="{
							   checkStrictly: true,
							   label:'name',
							   value:'id'
							}"
                       clearable></el-cascader>
        </el-form-item>
        <el-form-item label="基本信息">
          <!--<el-input type="textarea" v-model="carForm.carDetail.info"></el-input>-->
          <quill-editor v-model="carForm.carDetail.info" :options="quillOptions">
          </quill-editor>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="carFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="save" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>

<!--  店铺入驻-->
    <el-dialog title="新增&编辑" :visible.sync="shopmall" :close-on-click-modal="false" style="width: 100%">
    <el-form :model="shop"  ref="shopForm"  label-position="left" label-width="40px" class="demo-ruleForm login-container">
      <h3 class="title">店铺信息</h3>
      <el-form-item prop="name"label="旺铺名称">
        <el-input type="text" v-model="shop.name" auto-complete="off" placeholder="请输入店铺名称！"></el-input>
      </el-form-item>
      <el-form-item prop="tel" label="座机">
        <el-input type="text" v-model="shop.tel" auto-complete="off" placeholder="请输入座机！"></el-input>
      </el-form-item>
      <el-form-item prop="address" label="店铺地址">
        <el-input type="text" v-model="shop.address" auto-complete="off" placeholder="选择地址！"></el-input>
        <el-button size="small" type="primary" @click="selectAdrress">选择</el-button>
      </el-form-item>
      <!--店铺-->
      <el-form-item prop="logo" label="店铺Logo">
        <!--        <el-input type="text" v-model="shop.logo" auto-complete="off" placeholder="请输入logo！"></el-input>-->
        <el-upload
            class="upload-demo"
            action="http://localhost:8081/commons/upload"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            :file-list="fileList"
            list-type="picture">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
        </el-upload>
      </el-form-item>

      <h3 class="title">管理员信息设置</h3>
      <el-form-item prop="admin.username" label="账号">
        <el-input type="text" v-model="shop.admin.username" auto-complete="off" placeholder="请输入账号！"></el-input>
      </el-form-item>
      <el-form-item prop="admin.phone" label="手机号码">
        <el-input type="text" v-model="shop.admin.phone" auto-complete="off" placeholder="请输入电话！"></el-input>
      </el-form-item>
      <el-form-item prop="admin.email" label="电子邮件">
        <el-input type="text" v-model="shop.admin.email" auto-complete="off" placeholder="请输入邮件！"></el-input>
      </el-form-item>
      <el-form-item prop="admin.password" label="密码">
        <el-input type="password" v-model="shop.admin.password" auto-complete="off" placeholder="请输入密码！"></el-input>
      </el-form-item>
      <el-form-item prop="admin.confirmPassword" label="确认密码">
        <el-input type="password" v-model="shop.admin.confirmPassword" auto-complete="off" placeholder="请输入确认密码！"></el-input>
      </el-form-item>
      <el-form-item style="width:100%;">
        <el-button type="primary" style="width:100%;" @click.native.prevent="settledIn" >入驻</el-button>
      </el-form-item>
    </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="shopmall = false">取消</el-button>
        <el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>
    <el-dialog
        title="选择地址"
        :visible.sync="dialogVisable"
        width="30%">
      <baidu-map :center="{lng: 116.403765, lat: 39.914850}" :zoom="11">
        <bm-view class="map"></bm-view>
        <bm-control :offset="{width: '10px', height: '10px'}">
          <!--:sugStyle="{zIndex: 2100} 让搜索提示上浮-->
          <bm-auto-complete v-model="keyword" :sugStyle="{zIndex: 2100}">
            <div style="margin-bottom:10px">
              <input id="searchInput" type="text" placeholder="请输入关键字" class="searchinput"/>
              <el-button type="success" @click="selectAdrressConfirm">确定</el-button>
            </div>
          </bm-auto-complete>
        </bm-control>
        <bm-local-search :keyword="keyword" :auto-viewport="true" ></bm-local-search>
      </baidu-map>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisable=false">取 消</el-button>
        <el-button type="primary" @click="dialogVisable=false">确 定</el-button>
      </span>
    </el-dialog>


    <!--审核弹框-->
    <el-dialog title="审核" :visible.sync="review" :close-on-click-modal="false">
      <template scope="scope">
      <el-form :model="shop" label-width="80px"  ref="shopForm">
        <el-form-item prop="name"label="错误类型">
          <el-input type="text" v-model="shop.name" auto-complete="off" ></el-input>
        </el-form-item>

        <!--富文本编辑框-->
        <el-form-item label="驳回原因">
          <quill-editor v-model="carForm.carDetail.info" :options="quillOptions">
          </quill-editor>
        </el-form-item>
      </el-form>

        <el-button @click.native="review = false">取消</el-button>
        <el-button type="danger" size="small" @click.native="handle">驳回</el-button>
        <el-button type="success" size="small" @click.native="pass">通过</el-button>
<!--<el-button type="primary" @click.native="save" :loading="addLoading">提交</el-button>-->
      </template>
    </el-dialog>
    <!--驳回-->
    <el-dialog title="亲！请填写驳回原因哦( ^▽^ )" :visible.sync="reject" :close-on-click-modal="false">
      <el-form :model="shop" label-width="80px"  ref="shopForm">
        <!--富文本编辑框-->
        <el-form-item label="驳回">
          <quill-editor v-model="carForm.carDetail.info" :options="quillOptions">
          </quill-editor>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="reject = false">取消</el-button>
        <el-button type="primary" @click.native="save" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>

  </section>


</template>

<script>
import { quillEditor } from "vue-quill-editor"; // 在页面中引入富文本编辑框的组件
import 'quill/dist/quill.core.css';   // 引入样式
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import quillConfig from "../../common/js/quill-config"

export default {
  components:{
    quillEditor   // 如果key和value的名字一样,可以省略 quillEditor:quillEditor
  },
  data() {
    return {

      shopmall:false, //编辑页面默认关闭
      dialogVisable:false,
      table: false,
      dialog: false,
      loading: false,
      gridData: [{
        date: '',
        name: '',
        address: '  '
      }],
      quillOptions:quillConfig,
      //分页
      query:{
        currentpage:1,  // 当前页
        pageSize:10,  // 每页显示条数
        keyword:""  // 关键字
      },
      //数据
      pageInfo:{
        total:0,
        rows:[]
      },

      listLoading: false,
      sels: [],//列表选中列
      review:false,    //编辑界面默认关闭
      reject:false,  //驳回弹框

      carFormVisible: false,//新增修改界面是否显示
      carFormLoading: false,
      carFormRules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ]
      },
      employees:[],
      carTypeTree:[],
      addLoading:false,
      coverFileList:[],
      cartypes:[],
      //往后端传值
      saveForm: {
        id:null,
        name:'',
        tel:'',
        state:null,
        address:'',
        logo:'',
        admin: {
          id:null,
          realName:''
        }
      },
      //入驻审核里面的数据
      shop: {
        id:null,
        name:'',
        tel:'',
        state:null,
        address:'',
        logo:'',
        admin: {
          id:null,
          realName:''
        }
      },

      //日志
      loginfo:{
        //日志记录
        note:'',
        //日志类型
        operateType:null,
        //日志id
        shopId:"",
        //商店id
        operateId:""
      },
      errorForm:{
        adminId:null,  //店长id
        shopId:null,  //店铺id
        errorType: '',
        detailedMsg: ''
      },

      //新增修改界面数据
      carForm: {
        id:null,
        title:"",
        cover:"",
        saleprice:0,
        costprice:0,
        isnew:0,
        reigstertime:"",
        mileage:null,
        costeffective:0,
        rushsale:0,
        quasinewcar:0,
        transitivecountry:0,
        type:{
          id:null,
          name:""
        },
        brand:null,
        typeId:null,
        carDetail:{
          info:""
        }
      }
    }
  },
  methods: {



    //商家入驻
    addshop:function(){
      this.shopmall = true;
    },

    selectAdrressConfirm(){
      //获取值搜索框值,设置给地址
      var searchInputV=document.getElementById("searchInput").value;
      this.shop.address = searchInputV;
      //关闭对话框
      this.dialogVisable = false;
    }, //图片预览
    handlePreview(file) {
      console.log(file);
    },
    //提交入驻
    settledIn(){
      this.$refs.shopForm.validate((valid) => {
        //校验表单成功后才做一下操作
        if (valid) {
          this.$confirm('确认入驻吗？', '提示', {}).then(() => {
            //拷贝后面对象的值到新对象,防止后面代码改动引起模型变化
            let para = Object.assign({}, this.shop); //shop 本身这个参数里面就有店铺和管理员信息
            // 为了后台好接收，封装一个对象放到里面
            //判断是否有id有就是修改,否则就是添加
            console.log("csddcdzscsdcs")
            this.$http.post("/shop/settlement",para).then((res) => {
              if(res.data.success){
                this.$message({
                  message: '操作成功!',
                  type: 'success'
                });
                //重置表单
                this.$refs['shopForm'].resetFields();
                //跳转登录页面
                this.$router.push({ path: '/echarts' });
              }
              else{
                this.$message({
                  message: res.data.message,
                  type: 'error'
                });
                this.$message("error！请核对后再试")
              }

            });
          });
        }
      })
    },


    //弹框显示编辑界面
    handleEdit:function (index,row) {
      console.log(row,"++++++++++++++")
      //弹出弹框
      this.review = true;
      console.log("tttt",row)
      this.shop = row
      //数据回显
      // this.shop = Object.assign({},row);
      //this.getCars();  // 做分页查询
    },
    //驳回
    handle:function (index, row) {

      //状态
      this.$http.post("/shop/reject", this.errorForm)
          .then(res => {
            res = res.data;
            if (res.success){
              //发送成功，记录日志
              this.operateErrorLog();
              this.$message.success(res.message);
              /*
              * 跳转到入驻页面之后怎么做到数据回显？
              * */
            }else {
              this.$message.error(res.message);
            }
          })
      // 弹出弹框
      // this.reject = true;
      this.pass();
      //查询
      this.getCars();  // 做分页查询
    },
    //通过写入日志方法
    pass :function() {
      // 3 通过
      this.loginfo.operateType = 2,
          // 日志记录
          this.loginfo.note="审核通过待激活"
          this.$http.put("/shopOperateLog",this.loginfo)
              //后端返回数据
              .then(res => {
                if (res.data.success){

                  //调用更改店铺状态的方法
                  this.shopstate();
                }
              })
    },
    //修改店铺状态
    shopstate(){
      // 3 通过
          this.$http.put("/shop/updata",this.shop)
              .then(res =>{
                  if(res.data.code == 200){
                     this.sendmail()
                   // this.getCars()
                  }

                this.review = false;  // 关闭弹出框
                this.getCars();
              })
    },
    //邮件发送
    sendmail(){
      this.$http.post("/employee/emil",this.shop)
          .then(res => {
            res = res.data;
            if (res.success){
              this.$message.success(res.message);
            }else {
              this.$message.error(res.message);
            }
          })
    },

    /* 审核数据 */
    handleAudit(index,row){
      //显示审核弹框
      this.review = true;
      this.saveForm = row;
      //发送axios请求到后端进行数据审核
      this.$http.put("/shop/audit",row)
          .then(res => {
            res = res.data;
            if (!res.success){
              this.logInfo.shopId = row.id;
              this.errorForm.shopId = row.id;
              this.errorForm.adminId = row.admin.id;
              this.errorForm.errorType = res.message; //将返回的错误信息显示到弹框中
            }
          })
    },

    //显示新增界面
    handleAdd: function () {
      // 弹出弹框
      this.carFormVisible = true;
      // 清空双向绑定的数据,避免将上一次填写的数据带到下一次
      this.carForm =  {

      };
      // 调用查询车辆类型数,渲染下拉框
      this.getCarTypeTree();
      //调用查询车辆品牌，渲染下拉框
      this.getcartype();
    },

    // 成功回调
    coverHandleSuccess(response, file, fileList){
      this.carForm.cover = response.data;
    },
    //文件删除
    // file 当前要删除的文件  里面包含的response是后端上传接口返回的值
    // fileList 当前未被删除的所有的文件
    coverHandleRemove(file, fileList) {
      var filePath =file.response.resultObj;    // 当前要删除文件的url地址
      this.$http.delete("/fastdfs?path="+filePath)
          .then(res=>{
            if(res.data.success){
              this.$message({
                message: '删除成功!',
                type: 'success'
              });
              // 将shop.logo设置为null,避免将已经删除的图片的路径带到数据库
              this.carForm.cover = "";
            }else{
              this.$message({
                message: '删除失败!',
                type: 'error'
              });
            }
          })
    },
    search(){
      this.query.currentpage = 1;
      this.getCars();
    },
    handleCurrentChange(val) {  // val是当前页
      this.query.currentpage = val;
      this.getCars();
    },
    //获取列表
    getCars() {
      this.listLoading = true;  // 弹出加载框
      this.$http.post("/shop",this.query)   // axios.defaults.baseURL+/car  http://localhost:80/api/car
          .then(result => {
            console.log(result)
            // success: true, message: "操作成功!", code: 200,响应的是一个对象
            let{success,message,data} = result.data; // result.data  {success:true,message:"",result:{total:1,rows:[]}}
            console.log("result",result)
            console.log("result+data",result.data)
            if(success){
              this.pageInfo.total = data.total;
              // 打印到页面
              this.shop.rows = data.data;
              this.listLoading = false;  // 关闭加载框
            }else{
              this.$message({message: '查询分页失败!'+result.message, type: 'error'});
            }
          })
          .catch(result => {
            this.$message({message: "查询分页失败!", type: 'error'});
          })
    },
    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.delete("/shop/"+row.id)
            .then(result => {
              result = result.data;
              if(result.success){
                this.$message({message: '删除成功', type: 'success'});
                // 刷新列表
                this.query.currentpage = 1;
                this.getCars();
                this.listLoading = false;  // 关闭弹出框
              }else{
                this.$message({message: '删除失败!'+result.message, type: 'error'});
              }
            })
      }).catch(() => {
        this.$message({message: '已取消删除', type: 'info'});
      });
    },
    getEmployeeList(){
      this.$http.get("/employee")
          .then(result => {
            result = result.data;
            if(result.success){
              this.employees = result.result;
            }else{
              this.$message({message: '获取员工列表失败!'+result.message, type: 'error'});
            }
          }).catch(result => {
        this.$message({message: '获取员工列表失败!', type: 'error'});
      })
    },

    /*
    * .then(res => {: 这是Promise的.then方法，它处理HTTP响应。当HTTP GET请求成功并返回数据时，这个函数将被调用。res参数包含了HTTP响应的内容。
    * */
    getcartype(){
      this.$http.get('/carType/getTypes')
          .then(res => {

            if(res.data.success){
              this.cartypes = res.data.data;
            }
          })
    },
    getCarTypeTree(){
      this.$http.get('/carType/treeData')
          .then(res => {
            if(res.data.success){
              this.carTypeTree = res.data.data;
            }
          })
    },
    //新增修改保存方法
    save: function () {
      this.$refs.carForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.carFormLoading = true;
            let para = Object.assign({}, this.carForm);
            // 处理车辆类型,如果选择了车辆类型的话,它双向绑定的type是一个数组,将数组的最后一个位置的值赋值给typeId
            debugger;
            if(para.type && para.type.length > 0){
              para.typeId = para.type[para.type.length-1];
            }

            this.$http.put("/shop",para)
                .then(result => {
                  result = result.data;
                  if(result.success){
                    this.$message({message: '保存成功', type: 'success'});
                    this.carFormLoading = false;
                    this.query.currentpage = 1;
                    this.getCars();
                    this.carFormVisible = false;
                  }else{
                    this.$message({message: '保存失败!'+result.message, type: 'error'});
                  }
                }).catch(result => {
              this.$message({message: '保存失败!', type: 'error'});
            })
          });
        }
      });
    },
    selsChange: function (sels) {
      this.sels = sels;
    },
    //批量删除
    batchRemove: function () {
      var ids = this.sels.map(item => item.id).toString();
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        let para = { ids: ids };
        batchRemoveUser(para).then((res) => {
          this.listLoading = false;
          //NProgress.done();
          this.$message({
            message: '删除成功',
            type: 'success'
          });
          this.getCars();
        });
      }).catch(() => {

      });
    }

  },
  mounted() {
    this.getCars();  // 做分页查询
  }
}

</script>

<style scoped>

</style>
